﻿using Commons.ReturnData;
using Microsoft.EntityFrameworkCore;
using OpenAI.Domain.Entities;
using OpenAI.Domain.IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenAI.Infrastructure.Repositories
{
    public class ChatTipRepository : IChatTipRepository
    {
        private readonly ChatDbContext context;

        public ChatTipRepository(ChatDbContext context)
        {
            this.context = context;
        }

        public async Task<SingleResult> CreateTipAsync(ChatTip chatTip)
        {
            context.ChatTips.Add(chatTip);
            try
            {
                await context.SaveChangesAsync();
                return new SingleResult();
            }
            catch (Exception)
            {

                return new SingleResult(false);
            }
        }

        public async Task<SingleResult> DeletedTipByIdAsync(int id)
        {
            var tip = await context.ChatTips.FindAsync(id);
            if(tip != null)
            {
                tip.SoftDelete();
                context.ChatTips.Remove(tip);
                await context.SaveChangesAsync();
                return new SingleResult();
            }
            else
            {
                return new SingleResult(false);
            }
        }

        public async Task<ChatTip?> FindChatTipByIdAsync(int id)
        {
            return await context.ChatTips.FindAsync(id);
        }

        public async Task<DataResult<ChatTip>> GetChatTipsAsync(Guid appUserId)
        {
            var tips = await context.ChatTips.OrderBy(x=>x.CreationTime).ToListAsync();
            return new DataResult<ChatTip>(tips.Count, tips);
        }

        public async Task<SingleResult> UpdateTipAsync(ChatTip chatTip)
        {
            context.ChatTips.Update(chatTip);
            try
            {
                await context.SaveChangesAsync();
                return new SingleResult();
            }
            catch (Exception)
            {

                return new SingleResult(false);
            }
        }
    }
}
